﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.ComponentModel;

namespace PTA.Web
{
    /// <summary>
    /// 回车提交控件
    /// </summary>
    [ToolboxData("<{0}:SubmitTextBox runat=server></{0}:SubmitTextBox>")]
    public class SubmitTextBox : System.Web.UI.WebControls.TextBox
    {
        /// <summary>
        /// 控件ID
        /// </summary>
        public string TargetContorlClientID
        {
            get
            {
                return (string)ViewState["TargetContorlClientID"] ?? string.Empty;
            }
            set
            {
                if (value == null || value.Trim().Length == 0)
                {
                    throw new ArgumentNullException();
                }
                ViewState["TargetContorlClientID"] = value;
            }
        }

        /// <summary>
        /// 呈现控件
        /// </summary>
        /// <param name="e">事件</param>
        protected override void OnPreRender(EventArgs e)
        {
            if (!this.Page.ClientScript.IsClientScriptBlockRegistered("SubmitControlPostBack"))
            {
                string postbackscript = "function SubmitCtlPostBack(evt,cid){var e=evt?evt:window.event;if(e.keyCode == 13){document.getElementById(cid).click();e.returnValue=false;}}";
                this.Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "SubmitControlPostBack", postbackscript, true);
            }
            if (TargetContorlClientID.Length > 0)
            {
                this.Attributes.Add("onkeydown", string.Format("return SubmitCtlPostBack(event,'{0}')", TargetContorlClientID));
            }
        }
    }
}
